package com.example.administrator.androidapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class Ch4Activity5 extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    private ArrayList arrayList;//暂存所有选中的复选框
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_ch4_5);

        arrayList=new ArrayList();
        //找到整个界面的容器
        LinearLayout linearLayout=(LinearLayout)findViewById(R.id.ch4_5_ll);
        //遍历所有的子元素
        int count=linearLayout.getChildCount();//子元素的个数
        for(int i=0;i<count;i++){
            View view=linearLayout.getChildAt(i);//得到某个子元素
            //区分是否是复选框
            if(view instanceof CheckBox){
                CheckBox checkBox=(CheckBox)view;
                checkBox.setOnCheckedChangeListener(this);
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        //参数b代表当前选项是否选中，compoundButton代表当前用户点击的复选框
        if(b){
            arrayList.add(compoundButton);
        }else {
            arrayList.remove(compoundButton);
        }

        //arrayList始终保存着已选中的复选框
        String all="";
        for (int i=0;i<arrayList.size();i++){
            CheckBox checkBox=(CheckBox)arrayList.get(i);
            String content=checkBox.getText().toString();
            all+=content+",";
        }
        TextView textView=(TextView)findViewById(R.id.ch4_5_tv);
        textView.setText(all);
    }
}
